<template>
  <div class="login_panel">
    <n-card title="后台登录" header-style="font-size:30px;font-weight: bold;font-family: 楷体;"
      content-style="font-size:20px;font-family: 楷体;" footer-style="font-size:30px;font-weight: bold;font-family: 楷体;">

      <n-form :rules="rules" :model="login">
        <n-form-item path="account" lable="账号">
          <n-input v-model:value="login.account" placeholder="请输入账号" />
        </n-form-item>

        <n-form-item path="password" lable="密码">
          <n-input v-model:value="login.password" type="password" placeholder="请输入密码" />
        </n-form-item>
      </n-form>

      <template #footer>
        <n-checkbox v-model:checked="login.rember" label="记住我" />
        <n-button type="warning" @click="register">登录</n-button>
      </template>
    </n-card>
  </div>
</template>
 
<script setup>
import { ref, reactive, inject } from 'vue'
import {
  NCard, NForm, NFormItem,
  NButton, NCheckbox, NInput,
} from 'naive-ui'
import { AdminStore } from '../stores/manager'
import { useRouter, useRoute } from 'vue-router'
const router = useRouter()
const route = useRoute()

const axios = inject('axios')
const message = inject('message')


// 验证规则
let rules = {
  account: [
    { required: true, message: '请输入账号！', trigger: 'blur' },
    { min: 1, max: 20, message: '账号长度在 1 到 20 个字符之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码！', trigger: 'blur' },
    { min: 3, max: 20, message: '账号长度在 3 到 20 个字符之间', trigger: 'blur' }
  ]
}

// 登录数据
let login = reactive({
  account: localStorage.getItem('account') || '',  // 用户名
  password: localStorage.getItem('password') || '',  // 密码
  rember: localStorage.getItem('rember') == 1,  // 记住你
})

// 发送请求
let register = async () => {
  const { data: res } = await axios.post('login', { login: login.account, password: login.password })
  if (res.status.code == 200) {
    message.info('欢迎回来！')
    let adminStore = AdminStore()
    adminStore.id = res.data.id
    adminStore.login = res.data.login
    adminStore.token = res.data.token
    adminStore.rember = login.rember
    if (login.rember) {
      localStorage.setItem('account', adminStore.login)
      localStorage.setItem('password', login.password)
      localStorage.setItem('rember', adminStore.rember ? 1 : 0)
      localStorage.setItem('token',res.data.token)
    }

    // 路由跳转
    router.push('/backstage')

  } else {
    return message.error('登录失败！');
  }

}
</script>
 
<style lang='less' scoped>

.login_panel {
  width: 400px;
  margin: 130px auto 0;
  position: absolute;
  left: 50%;
  top: 30%;
  transform: translate(-50%, -50%);

  .n-card {
    background-color: rgb(172, 177, 206);
  }

  .n-button {
    color: black;
    font-weight: bold;
  }
}
</style>